import { defineStore } from 'pinia';

type ListType = {
  id: number;
  name: string;
  done: boolean;
}[];

type ActionTypeString = 'All' | 'Active' | 'Completed';

const useTodosStore = defineStore('todos', {
  state() {
    return {
      list: JSON.parse(
        localStorage.getItem('todo_pinia_vue3_list') ||
          JSON.stringify([
            {
              id: 1,
              name: '吃饭',
              done: true,
            },
            {
              id: 2,
              name: '睡觉',
              done: false,
            },
            {
              id: 3,
              name: '打豆豆',
              done: false,
            },
          ])
      ) as ListType,
      type: JSON.parse(
        localStorage.getItem('todo_pinia_vue3_type') || 'All'
      ) as ActionTypeString,
    };
  },
  getters: {
    /** 小选影响全选 */
    checkAll(): boolean {
      return this.list.length > 0 && this.list.every((item) => item.done);
    },
    /** 计算未完成 */
    getNum(): number {
      return this.list.filter((item) => !item.done).length;
    },
    /** 根据类型计算数组 */
    Todos_List(): ListType {
      return this.list.filter((item) => {
        if (this.type === 'All') return item;
        if (this.type === 'Active') return !item.done;
        return item.done;
      });
    },
  },
  actions: {
    /** 添加 */
    handleAdd(content: string) {
      this.list.unshift({
        id: Date.now(),
        name: content,
        done: false,
      });
    },
    /** 删除 */
    handleDel(id: number) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    /** 选择框 */
    handlecheck(id: number) {
      this.list = this.list.map((item) => {
        return { ...item, done: item.id === id ? !item.done : item.done };
      });
    },
    /** 全选影响小选 */
    handlecheckAll(done: boolean) {
      this.list.forEach((item) => (item.done = done));
    },
    /** 改变类型 */
    handleChangeType(type: ActionTypeString) {
      this.type = type;
    },
    /** 清空已完成 */
    handleClear() {
      this.list = this.list.filter((item) => !item.done);
    },
  },
});

export default useTodosStore;
